import React, { memo, useCallback, useEffect, useState } from 'react';
import { Form, message, Select, Table, Button, Popconfirm } from 'antd';
import LimitInput from '@/components/LimitInput';
import { Icon, Operates } from '@/pages/Recruitment/components';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getSeverLaborSettingList, handleHandoverFlowEdit } from '@/pages/TurnoverSetting/LeaveSetting/services';
import styles from './index.less';

const { Option } = Select;

const economicList = [
    { value: '有', key: 1 }, { value: '无', key: 0 }
];
const requireList = [
    { value: '无需证明', key: '1' }, { value: '附件证明', key: '2' }, { value: '制度关联', key: '3' }
];
const SeverLaborTable = memo(({ form }) => {
    const { getFieldDecorator, validateFields } = form;
    const [dataSource, setDataSource] = useState([]);
    const [originDataSource, setOriginDataSource] = useState([]);
    const [currentId, setCurrentId] = useState('');

    const { data: tableData = [], run, loading } = useRequest(getSeverLaborSettingList, {
        ...defaultFormatResult
    });
    const { run: editRun, loading: editLoading } = useRequest(handleHandoverFlowEdit, {
        manual: true,
        ...defaultFormatResult
    });

    const genUUID = useCallback(
        (length = 14) =>
            Number(
                Math.random()
                    .toString()
                    .substr(3, length) + Date.now()
            ).toString(36),
        []
    );
    const handleDataSource = dataList => {
        const data = [];
        dataList.forEach(item => {
            const mainId = genUUID();
            const { severTypeInfo, compensationFlag } = item;
            item.severLaborRelationDetailList.forEach((v, i) => {
                const params = {
                    ...v,
                    mainId,
                    severTypeInfo,
                    compensationFlag,
                    proofRequirementType: v.proofRequirementType.split(',')
                };
                if (i === 0) {
                    params.rowLength = item.severLaborRelationDetailList.length
                }
                data.push(params);
            })
        });
        console.log(data);
        setDataSource(data);
        setOriginDataSource(JSON.parse(JSON.stringify(data)));
    };

    const handleEditStatus = record => {
        const { mainId } = record;
        let count = 0; // 当前类型的数据总数
        let first = -1; // 当前类型第一条数据的索引
        const data = dataSource.map((item, index) => {
            if (mainId === item.mainId) {
                if (first === -1) first = index;
                // eslint-disable-next-line no-plusplus
                count++;
            }
            return item;
        });
        // 往当前类型数据的最后一条，插入添加按钮
        data.splice(first + count, 0, { isButton: true, mainId, uuid: genUUID() });
        const index = data.findIndex(item => mainId === item.mainId);
        // 添加了按钮，则需要rowLength + 1
        data[index] = {
            ...data[index],
            rowLength: count + 1
        };
        setCurrentId(record.mainId);
        setDataSource(data);
    };

    const handleAddCondition = (record, index) => {
        // index为添加按钮的索引
        const firstIndex = dataSource.findIndex(item => item.mainId === record.mainId);
        const data = dataSource.slice();
        // 设置rowLength + 1
        data[firstIndex] = {
            ...data[firstIndex],
            rowLength: data[firstIndex].rowLength + 1
        };
        const newData = {
            ...data[firstIndex],
            rowLength: 0,
            uuid: genUUID(),
            applyScene: undefined,
            proofRequirementType: undefined
        };
        delete newData.id;
        // 往添加按钮前插入数据
        data.splice(index, 0, newData);
        setDataSource(data);
    };

    const handleDeleteCondition = record => {
       const data = dataSource.slice();
       const { id, mainId, uuid } = record;
       let index = -1; // 当前类型第一条数据的索引
       let currentIndex = -2; // 当前数据索引
        // eslint-disable-next-line no-plusplus
       for (let i = 0; i < data.length; i++) {
           if (data[i].mainId === mainId && index === -1) index = i;
           if (data[i].id ? data[i].id === id : data[i].uuid === uuid) {
               currentIndex = i;
               break;
           }
       }
       // 将当前类型数据第一条数据的rowLength - 1，
       data[index] = { ...data[index], rowLength: data[index].rowLength - 1 };
       if (index === currentIndex) {
           // 如果当前数据与当前类型第一条数据相同，要讲rowLength往下赋值
           data[index + 1] = { ...data[index + 1], rowLength: data[index].rowLength };
       }
       // 删除数据
       data.splice(currentIndex, 1);
       setDataSource(data);
    };

    const getRequireName = (arr = []) => {
        if (!arr) return '';
       return arr.map(item => requireList.find(v => v.key === item)?.value)?.join('，')
    };

    const handleChangeDataSource = ({ data, type, value }, isSingle = true) => {
        const { id, mainId, uuid } = data;
        if (isSingle) {
            const index = dataSource.findIndex(item => item.id ? item.id === id : item.uuid === uuid);
            dataSource[index][type] = value;
        } else {
            dataSource.forEach(item => {
                if (item.mainId === mainId) {
                    item[type] = value;
                }
            })
        }
    };

    const handleSave = () => {
        validateFields(error => {
            if (!error) {
                const data = dataSource.filter(item => !item.isButton); // 将按钮排除出去
                const index = data.findIndex(item => item.mainId === currentId); // 找到改类型第一条数据
                // eslint-disable-next-line operator-assignment
                data[index].rowLength = data[index].rowLength - 1; // 去除按钮，更新rowLength

                const curData = data.filter(item => item.mainId === currentId);
                const { compensationFlag, severTypeInfo } = curData?.[0];
                editRun({
                    compensationFlag,
                    severLaborRelationDetailList: curData.map(item => {
                        const params = {
                            applyScene: item.applyScene,
                            proofRequirementType: item.proofRequirementType.join(',')
                        };
                        if (item.id) {
                            params.id = item.id;
                        }
                        return params
                    }),
                    severType: severTypeInfo?.severType
                }).then(() => {
                    setCurrentId('');
                    run()
                })
            }
        })
    };


    // eslint-disable-next-line no-nested-ternary
    const renderEconomic = (text, record) => record.mainId === currentId ? (
        <Form.Item>
            {getFieldDecorator(`compensationFlag-${record.id || record.uuid}`, {
                    initialValue: `${record.compensationFlag}` || '0',
                    rules: [{ required: !record.isButton, message: '请选择' }]
                })(
                    <Select
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        onChange={value => handleChangeDataSource({ data: record, type: 'compensationFlag', value }, false)}
                    >
                        { economicList.map(item => <Option key={item.key}>{item.value}</Option>) }
                    </Select>
                )}
        </Form.Item>
        ) : `${record.compensationFlag}` === '1' ? '有' : '无';

    const renderInput = (text, record) => record.mainId === currentId ? (
        <Form.Item>
            {getFieldDecorator(`applyScene-${record.id || record.uuid}`, {
                    initialValue: record.applyScene,
                    rules: [{ required: true, message: '请输入' }]
                })(
                    <LimitInput
                        area
                        maxLength={200}
                        placeholder="请输入"
                        autoSize={{ minRows: 2, maxRows: 2 }}
                        onChange={e => {
                            handleChangeDataSource({
                                data: record,
                                type: 'applyScene',
                                value: e.target.value
                            })
                        }}
                    />
                )}
        </Form.Item>
        ) : record.applyScene;

    const getValueFromEvent = args => {
        if (args.length >= 2) {
            if (args[args.length - 1] === '1') return ['1'];
            const index = args.indexOf('1');
            if (index !== -1) {
                return args.slice(index + 1);
            }
        }
        return args
    };
    const renderRequired = (text, record) => record.mainId === currentId ? (
        <Form.Item>
            <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', lineHeight: 1 }}>
                {getFieldDecorator(`proofRequirementType-${record.id || record.uuid}`, {
                    initialValue: record.proofRequirementType,
                    rules: [
                        { required: true, message: '请选择' }
                    ],
                    getValueFromEvent
                })(
                    <Select
                        style={{ width: '100%', marginRight: 8 }}
                        mode="multiple"
                        placeholder="请选择"
                        onChange={value => {
                            handleChangeDataSource({
                                data: record,
                                type: 'proofRequirementType',
                                value: getValueFromEvent(value)
                            });
                        }}
                    >
                        { requireList.map(item => <Option key={item.key}>{item.value}</Option>) }
                    </Select>
                )}
                <Popconfirm
                    getPopupContainer={trigger => trigger.parentNode}
                    title="你确定要删除这行内容吗？"
                    onConfirm={() => {
                        handleDeleteCondition(record);
                    }}
                    disabled={dataSource?.filter(item => item.mainId === currentId)?.length <= 2}
                >
                    <Icon
                        type="DeleteIcon"
                        title="删除"
                        disabled={dataSource?.filter(item => item.mainId === currentId)?.length <= 2}
                    />
                </Popconfirm>
            </div>
        </Form.Item>
        ) : getRequireName(record.proofRequirementType);

    const columns = [
        {
            title: '解除类型',
            dataIndex: 'severTypeInfo',
            render: (text, record) => {
                const obj = {
                    children: text?.severTypeName || '--',
                    props: { rowSpan: 0 }
                };
                if (record.rowLength) {
                    obj.props.rowSpan = record.rowLength;
                }
                return obj;
            }
        },
        {
            title: '经济补偿金',
            dataIndex: 'compensationFlag',
            width: 120,
            render: (text, record) => {
                const obj = {
                    children: renderEconomic(text, record),
                    props: { rowSpan: 0 }
                };
                if (record.rowLength) {
                    obj.props.rowSpan = record.rowLength;
                }
                return obj;
            }
        },
        {
            title: '适用情形',
            dataIndex: 'applyScene',
            render: (text, record, index) => {
                const { isButton } = record;
                if (!isButton) {
                    return renderInput(text, record);
                }
                const limit = dataSource?.filter(item => item.mainId === currentId)?.length >= 20;
                return {
                    children: <Button
                        style={{ display: limit ? 'none' : 'block' }}
                        block
                        type="dashed"
                        onClick={() => handleAddCondition(record, index)}
                        disabled={limit}
                    >
                        + 添加问题
                    </Button>,
                    props: { colSpan: 2 }
                }
            }
        },
        {
            title: '举证要求',
            dataIndex: 'proofRequirementType',
            width: 200,
            render: (text, record) => {
                const { isButton } = record;
                if (!isButton) {
                    return renderRequired(text, record);
                }
                return {
                    props: { colSpan: 0 }
                }
            }
        },
        {
            title: '操作',
            width: 120,
            render: (text, record) => {
                const { mainId } = record;
                const operates = mainId === currentId
                    ? [
                        <Icon
                            type="confirm_o"
                            title="保存"
                            onClick={() => {
                               handleSave();
                            }}
                        />,
                        <Icon
                            type="cancel_o"
                            title="取消"
                            onClick={() => {
                                setDataSource(JSON.parse(JSON.stringify(originDataSource)));
                                setCurrentId('');
                            }}
                        />
                    ]
                    : [
                        <Icon
                            type="listfunction_edit_icon_default"
                            title="编辑"
                            disabled={record.mainId !== currentId && currentId}
                            onClick={() => {
                                if (currentId) {
                                    message.error('请先完成编辑！');
                                    return;
                                }
                                handleEditStatus(record);
                            }}
                        />
                    ];

                const obj = {
                    children: <Operates operates={operates} />,
                    props: { rowSpan: 0 }
                };
                if (record.rowLength) {
                    obj.props.rowSpan = record.rowLength;
                }
                return obj;
            }
        }
    ];

    useEffect(() => {
        if (tableData && tableData.length) {
            handleDataSource(tableData)
        }
    }, [tableData]);
    return (
        <Table
            rowKey={record => record.id || record.uuid}
            className={styles.tableWrap}
            rowClassName={styles.tableRowWrap}
            loading={loading || editLoading}
            dataSource={dataSource}
            columns={columns}
            pagination={false}
        />
    );
});
export default Form.create()(SeverLaborTable);
